using System;

namespace PropertyExpression.CalcExpression
{
    internal class CollectionResultValue<TEntity, TProperty> : IValue<TProperty> where TEntity : class
    {
        private readonly EntitySetWrapper<TEntity> entitySet;
        private readonly Func<ICalc<TEntity, TProperty>> calcFunc;

        public CollectionResultValue(EntitySetWrapper<TEntity> entitySet, Func<ICalc<TEntity, TProperty>> calcFunc)
        {
            this.entitySet = entitySet;
            this.calcFunc = calcFunc;

            NewResult();

            entitySet.CollectionChanged += EntitySet_OnCollectionChanged;
        }

        private void EntitySet_OnCollectionChanged()
        {
            result.Changed -= Result_OnChanged;
            NewResult();

            OnChanged();
        }

        private IValue<TProperty> result;

        public TProperty PrimVal
        {
            get
            {
                return result.PrimVal;
            }
        }

        private void NewResult()
        {
            var calc = calcFunc();
            calc.BeforeCalc();
            foreach (TEntity entity in entitySet)
            {
                calc.Calc(entity);
            }
            calc.AfterCalc();
            result = calc.Result;
            result.Changed += Result_OnChanged;
        }

        private void Result_OnChanged()
        {
            OnChanged();
        }

        private void OnChanged()
        {
            if (Changed != null) Changed();
        }

        public event Action Changed;

        public override string ToString()
        {
            return PrimVal.ToString();
        }
    }
}